package leetcode.code1652;

import java.util.Arrays;

public class Solution {
	public int[] decrypt(int[] code, int k) {
		if (k == 0) {
			Arrays.fill(code, 0);
			return code;
		}
		int len = code.length;
		int[] sums = new int[len];
		sums[0] = code[0];
		for (int i = 1; i < sums.length; i++) {
			sums[i] = code[i] + sums[i - 1];
		}
		int[] ans = new int[len];
		if (k > 0) {
			for (int i = 0; i < ans.length; i++) {
				int index = i + k;
				if (index < len) {
					ans[i] = sums[index] - sums[i];
				} else {
					ans[i] = sums[len - 1] - sums[i] + sums[index - len];
				}
			}
		} else {
			k = -k;
			for (int i = 0; i < ans.length; i++) {
				if (i == k) {
					ans[i] = sums[i - 1];
				} else if (k < i) {
					ans[i] = sums[i] - sums[i - k - 1] - code[i];
				} else {
					ans[i] = sums[i] - code[i] + sums[len - 1] - sums[len - k + i - 1];
				}
			}
		}
		return ans;
	}
}
